package net.sansi.v3correctserver.service.analyse;

import net.sansi.v3correctserver.constenum.AppHelper;
import net.sansi.v3correctserver.constenum.FilenameGenerator;
import net.sansi.v3correctserver.dto.analyse.PhotoAnalyseDto;
import net.sansi.v3correctserver.entity.analyse.PhotoAnalyseResult;
import net.sansi.v3correctserver.entity.image.RecImage;
import net.sansi.v3correctserver.entity.screen.CorrectArea;
import net.sansi.v3correctserver.entity.screen.Screen;
import net.sansi.v3correctserver.entity.space.CorrectCnf;
import net.sansi.v3correctserver.service.photorec.RecService;
import net.sansi.v3correctserver.service.photorec.rec.RecFence;
import net.sansi.v3correctserver.service.space.ProjectSpace;
import net.sansi.v3correctserver.service.takeshowphoto.TakeShowPhotoService;
import net.sansi.v3correctserver.task.AutoAnalysePhotoTask;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.file.Path;
import java.util.List;

/**
 * Created by Fang
 * create time : 2024/11/1
 * IDE : IntelliJ IDEA
 * <p>
 * 相片分析服务
 */
@Service
public class AnalyseService {

    @Resource
    private RecService recService;

    /**
     * 矩形屏相片分析
     *
     * @param form 矩形屏相片分析请求
     * @return 矩形屏相片分析结果
     */
    public PhotoAnalyseResult.Rect rectPhoto(PhotoAnalyseDto.RectPhotoReq form) {
        return recService.rectPhoto(
                RecImage.load(Path.of(form.getLedPath())),
                form.getBlackPath() == null ? null : RecImage.load(Path.of(form.getBlackPath())),
                form.getFence()
        );
    }

    /**
     * 矩形屏相片分析（需要拍摄）
     *
     * @param form 矩形屏相片分析请求
     * @return 分析结果
     */
    public PhotoAnalyseResult.Rect rectTake(PhotoAnalyseDto.RectTakeReq form) {
        ProjectSpace projectSpace = AppHelper.projectSpace();
        CorrectCnf correctCnf = projectSpace.getCorrectCnf();
        int areaId = form.getAreaId();
        CorrectArea area = correctCnf.getArea(areaId);
        RecImage black = takeShowPhotoService.takeBlack2Image(
                form.getCameraParams(),
                projectSpace.analyseSpace().resolveFilename(FilenameGenerator.blackPhoto(
                        correctCnf.getCamera(),
                        areaId,
                        form.getColorIdx()
                ))
        );
        RecImage ledPhoto = takeShowPhotoService.take2Image(
                area,
                correctCnf.getCameraParams().get(form.getColorIdx()).getBrightness(),
                form.getColorIdx(),
                0,
                correctCnf.getShowSpan(),
                form.getCameraParams(),
                projectSpace.analyseSpace().resolveFilename(FilenameGenerator.analysePhoto(
                        correctCnf.getCamera(),
                        form.getCameraParams(),
                        form.getColorIdx(),
                        areaId
                )), 0, 0
        );
        return recService.rectPhoto(ledPhoto, black, form.getFence());
    }


    @Resource
    private TakeShowPhotoService takeShowPhotoService;

    /**
     * 矩形屏相片分析（需要拍摄）
     *
     * @param form 矩形
     */
    public PhotoAnalyseDto.RectFenceResp rectFenceTake(PhotoAnalyseDto.RectTakeReq form) {
        ProjectSpace projectSpace = AppHelper.projectSpace();
        CorrectCnf correctCnf = projectSpace.getCorrectCnf();
        RecImage black = takeShowPhotoService.takeBlack2Image(
                form.getCameraParams(),
                projectSpace.analyseSpace().resolveFilename(FilenameGenerator.blackPhoto(
                        correctCnf.getCamera(),
                        form.getAreaId(),
                        form.getColorIdx()
                ))
        );
        RecImage ledPhoto = takeShowPhotoService.takeFence2Image(
                correctCnf.getArea(form.getAreaId()),
                form.getColorIdx(),
                projectSpace.analyseSpace().resolveFilename(FilenameGenerator.fullPhoto(
                        correctCnf.getCamera(),
                        form.getColorIdx(),
                        form.getAreaId()
                ))
        );
        RecFence recFence = new RecFence(ledPhoto, black);
        return new PhotoAnalyseDto.RectFenceResp().setFence(recFence.searchFence())
                .setBlackPath(black.getPath().toString())
                .setLedPath(ledPhoto.getPath().toString());
    }

    /**
     * 自动分析
     *
     * @param form 自动分析请求
     * @return 任务id
     */
    public String startAutoAnalysePhoto(PhotoAnalyseDto.RectAutoReq form) {
        AutoAnalysePhotoTask task = new AutoAnalysePhotoTask(form);
        AppHelper.getTaskManager().addTask(task, true);
        return task.getTaskId();
    }

    /**
     * 自动计算区域
     *
     * @return 自动计算区域
     */
    public List<CorrectArea> autoComputeArea(PhotoAnalyseDto.RectAutoSplitAreaReq form) {
        CorrectCnf correctCnf = AppHelper.projectSpace().getCorrectCnf();
        Screen screen = new Screen();
        screen.setWidth(correctCnf.getScreenWidth());
        screen.setHeight(correctCnf.getScreenHeight());
        List<CorrectArea> areas = new AutoSplitArea(
                screen,
                correctCnf.getCorrectRange(),
                form.getMode(), form.getSpan(), form.getCol(),
                form.getRow()
        )
                .autoSplitArea();
        areas.forEach(area -> area.resetShowAreaByExtends(
                correctCnf.getShowExtendWidth(),
                correctCnf.getCorrectRange()
        ));

        // 执行配置文件分区数据更新并保存至文件
        correctCnf.setAreas(areas);
        AppHelper.projectSpace().saveCorrectCnf(correctCnf);
        return areas;
    }
}
